package com.cmcc.groupcontacts.firewall.business;

import java.util.ArrayList;
import java.util.Date;

import android.database.Cursor;
import android.provider.ContactsContract;

import com.cmcc.groupcontacts.firewall.dao.SmsListDAO;
import com.cmcc.groupcontacts.firewall.dao.model.SmsListVO;
import com.cmcc.groupcontacts.util.ExceptionHandler;
import com.cmcc.groupcontacts.util.StringUtil;

/**
 * 信息拦截记录业务处理类
 * 
 * @author
 * 
 */
public class SmsListBusiness extends BaseBusiness {
	public static final int TYPE_SMS = 0; // 类型-短信
	public static final int TYPE_MMS = 1; // 类型-彩信
	
	private SmsListDAO smsListDAO;

	public SmsListBusiness() {
		super();

		smsListDAO = new SmsListDAO();
	}

	/**
	 * 处理被拦截的短信：<br />
	 * 将被拦截的短信插入短信拦截记录。
	 */
	public long handleBlockedSms(String number, String body, int type) {
		try {
			// 将被拦截的短信插入短信拦截记录
			SmsListVO smsList = new SmsListVO();
			smsList.setNumber(number);
			smsList.setName(getContactsName(number));
			smsList.setDate(new Date().getTime());
			smsList.setType(type);
			smsList.setProtocal(0);
			smsList.setSubject(null);
			smsList.setBody(body);
			smsList.setRead(false);
			return smsListDAO.add(smsList);
			// TODO: 只保留100条拦截记录
		} catch (Exception e) {
			ExceptionHandler.handle(e, "处理被拦截的短信时出错");
			return -1;
		}
	}

	/*
	 * 获取联系人姓名
	 */
	private String getContactsName(String number) {
		Cursor cursor = null;
		String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME };
		String where = StringUtil.format("PHONE_NUMBERS_EQUAL({0},'{1}',0)", ContactsContract.CommonDataKinds.Phone.NUMBER, number);
		try {
			cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, where, null, null);
			if (cursor != null && cursor.moveToPosition(0)) {
				return cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
			} else {
				return null;
			}
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		}
	}

	/**
	 * 获取所有信息拦截记录
	 * 
	 * @return
	 */
	public ArrayList<SmsListVO> getSmsList() {
		String orderBy = SmsListVO.MetaData.DATE + " desc";
		return smsListDAO.query(false, SmsListVO.MetaData.ALL_COLS, null, null, null, null, orderBy, null);
	}

	/**
	 * 删除信息拦截记录
	 * 
	 * @param id
	 * @return
	 */
	public long delete(int id) {
		return smsListDAO.del(SmsListVO.MetaData.ID + "=" + id, null);
	}
}
